package com.tusuo.stds.ui.similarity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.Constants;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.SimilarityInfo;
import com.tusuo.stds.util.Utils;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(SimilarityResultPresenter.class)
class SimilarityResultPresenter extends MvpBasePresenter<SimilarityResultView> {

    @Inject
    ApiHelper mApiHelper;

    SharedPreferences mSharedPref;
    private Activity mActivity;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<SimilarityInfo> mGetSimilarityInfoSubscriber = null;

    private int mLevelRecordId;

    SimilarityResultPresenter(Context context) {
        mContext = context;
        mActivity = (Activity)mContext;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initSimilarityResultPresenterComponent().inject(this);
    }

    @Override
    public void attachView(SimilarityResultView view) {
        super.attachView(view);

        if (mSharedPref == null) {
            mSharedPref = PreferenceManager.getDefaultSharedPreferences(mActivity);
        }

        mSharedPref.edit().putLong(Constants.KEY_SIMILARITY_QUESTION_DATE,System.currentTimeMillis()).apply();

        mGetSimilarityInfoSubscriber = new GetSimilarityInfoSubscriber();
        mApiHelper.getSimilarityInfo(mGetSimilarityInfoSubscriber);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mGetSimilarityInfoSubscriber != null) {
            mGetSimilarityInfoSubscriber.unsubscribe();
            mGetSimilarityInfoSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    private class GetSimilarityInfoSubscriber extends Subscriber<SimilarityInfo> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final SimilarityInfo similarityInfo) {
            if (similarityInfo.checkState(mContext) && getView() != null) {
                getView().setSimilarityResult(similarityInfo);
            }
        }
    }
}
